package spike.pool;

import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

/**
 * Created by dmitry on 11/12/14.
 */
public class Main {
    public static void main(String[] args) {
        MyPoolFactory pf = new MyPoolFactory();

        MyConnectionPool<Socket> cp =  pf.newConnectionPool(10, 100, 1000, TimeUnit.MILLISECONDS, new MyConnectionSource());

        try {
            cp.start();
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        for (int i = 0; i < 1000; i++) {
            Thread td = new Thread(() -> {
                while (true) {
                    Socket s = null;
                    try {
                        s = cp.get();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (s != null)
                        cp.release(s);
                }
            });

            td.start();
        }


        for (int i = 0; i < 1000; i++) {
            Thread td = new Thread(() -> {
                while (true) {
                    Socket s = null;
                    s = cp.tryGet();


                    try {
                        Thread.currentThread().sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                    if (s != null) {
                        cp.release(s);
                    }
                }
            });

            td.start();
        }

        try {
            Thread.currentThread().sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        cp.stop();
    }
}
